package com.itheima.Demo;

import com.itheima.Utils.MybatisUtils;
import com.itheima.dao.UserMapper;
import com.itheima.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import java.util.List;


public class Demo01 {
    @Test//查询所有
    public void findaAlluser(){
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> list = mapper.findall();
        //System.out.println(list);
        for (User user : list) {
            System.out.println(user.toString());
        }
        sqlSession.close();
    }
  @Test//查询所有 并且映射到实体类中
    public void findall2(){
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> list = mapper.findall();
      System.out.println(list);
        for (User user : list) {
            System.out.println(user.toString());
        }
        sqlSession.close();
    }

    @Test//添加用户
    public void addUser(){
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.addUser(new User(null,"d","d","d",18,1));
        sqlSession.close();
    }

    @Test//添加用户并且获取他自增id的值
    public void addUser2(){
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User(null, "Harry", "124", "longlong", 19, 1);
        Integer integer = mapper.addUser2(user);
        System.out.println(user.getId());//返回用户id
        sqlSession.close();
    }

    @Test//修改指定id的用户信息
    public void updateUser(){
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateuser(new User(11L,"黄文龙","1010","dale",27,1));
        sqlSession.close();
    }

    @Test//删除指定id的值
    public void deleteUserById(){
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deletebyID("11");
        sqlSession.close();
    }
}
